const response = require('../response')
const fs = require('fs')
let path = require('path')
module.exports = {
  getAll(req, resp) {
    let data = fs.readFileSync(path.join(__dirname, '../public', 'data.json'), 'utf-8')

    if (!data) {
      response(resp, 402, '您还没有数据')
      return
    }
    if (data) {
      data = JSON.parse(data)
      response(resp, 200, '请求成功', data)
    }
  },
  add(req, resp) {
    let { username, password, email, tel, sex } = req.body
    if (!username || !password || !email || !tel || !sex) {
      response(resp, 401, '数据不能为空！')
      return
    }
    let data = fs.readFileSync(path.join(__dirname, '../public', 'data.json'), 'utf-8')
    let arr;
    if (data.length === 0) {
      arr = []
    } else {
      arr = JSON.parse(data)
    }
    let id = arr.length === 0 ? 1 : arr[(arr.length - 1)].id + 1;
    for (let key = 0; key < arr.length; key++) {
      if (arr[key].username === username) {
        response(resp, 405, '该用户以存在')
        return
      }
    }

    arr.push({ id, username, password, email, tel, sex })
    fs.writeFileSync(path.join(__dirname, '../public', 'data.json'), JSON.stringify(arr))

    response(resp, 200, '添加成功')
  },
  del(req, resp) {
    let { index } = req.body
    if (!index) {
      response(resp, 403, '数据不可以为空')
      return

    }
    let data = fs.readFileSync(path.join(__dirname, '../public', 'data.json'), 'utf-8')
    arr = JSON.parse(data)
    arr.splice(index, 1);
    fs.writeFileSync(path.join(__dirname, '../public', 'data.json'), JSON.stringify(arr))
    response(resp, 200, '请求成功')

  },
  getChange(req, resp) {
    let { index } = req.body
    if (!index) {
      response(resp, 403, '数据不可以为空')
      return

    }
    let data = fs.readFileSync(path.join(__dirname, '../public', 'data.json'), 'utf-8')
    arr = JSON.parse(data)[index]
    console.log(arr)
    response(resp, 200, '请求成功', arr)
  },
  change(req, resp) {
    let { index, username, password, email, tel, sex } = req.body
    if (!username || !password || !email || !tel || !sex || !index) {
      response(resp, 403, '数据不能为空！')
      return
    }
    let data = fs.readFileSync(path.join(__dirname, '../public', 'data.json'), 'utf-8')
    data = JSON.parse(data)
    obj = data[index]
    if (obj.username !== username) {
      obj.username = username
    }
    if (obj.password !== password) {
      obj.password = password
    }
    if (obj.email !== email) {
      obj.email = email
    }
    if (obj.tel !== tel) {
      obj.tel = tel
    }
    if (obj.sex !== sex) {
      obj.sex = sex
    }
    data[index] = obj

    fs.writeFileSync(path.join(__dirname, '../public', 'data.json'), JSON.stringify(data))

    response(resp, 200, '修改成功')
  }
}